package services

import (
	"fmt"
	"github.com/astaxie/beego/logs"
	"strings"
	"time"
)

//CallWhatDate 询问日期
func (this *systemCall) CallWhatDate(word string) (string, error) {
	p := make([]string, 0)

	//--------------解析语句获取参数，获取堆栈参数,0:日期 1:询问方式， 解析成功次数
	params, syncSuccessCnt, err := SystemParamServiceDefault.resolve("CallWhatDate", func(params *SysCallParams) error {
		//解析语句中的日期
		switch {
		case strings.Index(word, "今天") != -1:
			p = append(p, "今天")
			d := time.Now()
			params.SetParam(0, d)
		case strings.Index(word, "昨天") != -1:
			p = append(p, "昨天")
			d := time.Now().Add(-time.Hour*24)
			params.SetParam(0, d)
		case strings.Index(word, "明天") != -1:
			p = append(p, "明天")
			d := time.Now().Add(time.Hour*24)
			params.SetParam(0, d)
		case strings.Index(word, "前天") != -1:
			p = append(p, "前天")
			d := time.Now().Add(-time.Hour*48)
			params.SetParam(0, d)
		case strings.Index(word, "后天") != -1:
			p = append(p, "后天")
			d := time.Now().Add(time.Hour*48)
			params.SetParam(0, d)
		}
		//解析语句中的具体询问
		switch {
		case strings.Index(word, "几号") != -1:
			params.SetParam(1, "day")
		case strings.Index(word, "星期几") != -1:
			params.SetParam(1, "week_day")
		case strings.Index(word, "周几") != -1:
			params.SetParam(1, "week_day")
		}

		return nil
	})

	if err != nil {
		return "", err
	}

	//语句解析失败
	if syncSuccessCnt == 0 {
		return "你说什么", nil
	}

	//如果语句完全解析成功，则判断内联中是否有语句关联，没有则添加
	if syncSuccessCnt == 2 && this.innerWords[word] == "" {
		logs.Info("语句完全解析成功，且内联中没有该语句关联，则添加：", word)
		this.SetInnerWord(word, "CallWhatDate")
	}

	//--------------定义执行,执行结果可能会干扰情绪，原力等等东西
	d,ok := params.GetParam(0).(time.Time)
	if !ok {
		return "你问哪天呀", nil
	}
	way,_ := params.GetParam(1).(string)
	switch way {
	case "day":
		p = append(p, fmt.Sprintf("%d号", d.Day()))
	case "week_day":
		p = append(p, fmt.Sprintf("星期%d", d.Weekday()))
	default:
		p = append(p, "怎么呢")
	}

	//-----------接入情绪,根据以上执行产生的临时变化，计算情绪反馈
	qingXuP := make([]string, 0)
	response :=strings.Join(p, "")
	callCntObj := this.callCnt[response]
	if callCntObj == nil {
		callCntObj = new(SysCallCnt)
		this.callCnt[response] = callCntObj
	}
	if time.Now().Sub(callCntObj.LastDate) > time.Minute {
		logs.Info("超过忍耐时间，回归0")
		callCntObj.Cnt = 0
		callCntObj.LastDate = time.Now()
	} else {
		logs.Info("同一词请求次数+1")
		callCntObj.Cnt++
	}
	cc := callCntObj.Cnt
	switch {
	case cc == 2:
		qingXuP = append(qingXuP, "额，")
	case cc == 3:
		qingXuP = append(qingXuP, "唉，")
	case cc == 4:
		qingXuP = append(qingXuP, "你已经问了我4遍了，麻烦记住了，")
	case cc == 5:
		qingXuP = append(qingXuP, "你饶了我吧，唉，")
	}


	return strings.Join(qingXuP, "")+response, nil
}

